import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Button, message, Tag, Spin } from 'antd';
import { ArrowLeftOutlined, DeleteOutlined } from '@ant-design/icons';
import { datasetService } from '../services';

const DatasetDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [dataset, setDataset] = useState(null);
  const [loading, setLoading] = useState(true);

  // 从datasetService获取数据，这里不再需要单独的模拟数据

  useEffect(() => {
    fetchDatasetDetail();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchDatasetDetail = async () => {
    setLoading(true);
    try {
      // 使用datasetService获取数据集详情
      const data = await datasetService.getDatasetDetail(id);
      setDataset(data);
    } catch (error) {
      console.error('获取数据集详情失败:', error);
      message.error('获取数据集详情失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      // 使用datasetService删除数据集
      await datasetService.deleteDataset(id);
      message.success('数据集删除成功');
      navigate('/');
    } catch (error) {
      console.error('删除数据集失败:', error);
      message.error('删除数据集失败，请稍后重试');
    }
  };

  const handleBack = () => {
    navigate('/');
  };

  const getStatusTag = (status) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="default">待处理</Tag>;
      case 'PROCESSING':
        return <Tag color="processing">处理中</Tag>;
      case 'COMPLETED':
        return <Tag color="success">已完成</Tag>;
      case 'FAILED':
        return <Tag color="error">失败</Tag>;
      default:
        // 对于没有status字段的数据，添加默认状态
        return <Tag color="default">已创建</Tag>;
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 40 }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!dataset) {
    return (
      <div style={{ textAlign: 'center', padding: 40 }}>
        <h3>数据集不存在</h3>
        <Button type="primary" onClick={handleBack}>
          返回列表
        </Button>
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center' }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          style={{ marginRight: 16 }}
        >
          返回
        </Button>
        <h2 style={{ margin: 0 }}>数据集详情</h2>
      </div>

      <Card style={{ marginBottom: 20 }}>
        <h3>{dataset.name}</h3>
        <p style={{ color: '#666', marginTop: 8 }}>{dataset.description}</p>
      </Card>

      <Card title="基本信息" style={{ marginBottom: 20 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="数据集ID">{dataset.id}</Descriptions.Item>
          <Descriptions.Item label="状态">{getStatusTag(dataset.status)}</Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {new Date(dataset.createdAt).toLocaleString()}
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            {new Date(dataset.updatedAt).toLocaleString()}
          </Descriptions.Item>
          {dataset.lastAccessed && (
            <Descriptions.Item label="最后访问">
              {new Date(dataset.lastAccessed).toLocaleString()}
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      <Card title="数据统计" style={{ marginBottom: 20 }}>
        <Descriptions column={2}>
          {dataset.recordCount !== undefined && (
            <Descriptions.Item label="记录数">{dataset.recordCount.toLocaleString()}</Descriptions.Item>
          )}
          {dataset.fileCount !== undefined && (
            <Descriptions.Item label="文件数">{dataset.fileCount}</Descriptions.Item>
          )}
          {dataset.size && (
            <Descriptions.Item label="数据大小">{dataset.size}</Descriptions.Item>
          )}
          {dataset.processingTime && (
            <Descriptions.Item label="处理时长">{dataset.processingTime}</Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      <Card title="数据来源" style={{ marginBottom: 20 }}>
        <Descriptions column={1}>
          {dataset.sourceType && (
            <Descriptions.Item label="来源类型">
              {dataset.sourceType === 'local' ? '本地文件' : 
               dataset.sourceType === 's3' ? 'Amazon S3' : 
               dataset.sourceType === 'upload' ? '上传文件' : 
               dataset.sourceType}
            </Descriptions.Item>
          )}
          {dataset.sourcePath && (
            <Descriptions.Item label="来源路径">{dataset.sourcePath}</Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Button 
          type="primary" 
          danger 
          icon={<DeleteOutlined />}
          onClick={handleDelete}
        >
          删除数据集
        </Button>
      </div>
    </div>
  );
};

export default DatasetDetail;